import 'package:flutter/material.dart';

class TabBarWidget extends StatefulWidget {
  static const int BOTTOM_TAB = 1;
  static const int TOP_TAB = 2;
  final int type;
  final String hostTitle;
  final List<Widget> tabItems;
  final List<Widget> tabViews;
  final Color backgroundColor;
  final Color indicatorColor;
  final Widget title;
  final int initPage;
  final ValueChanged<int> onPageChanged;

  TabBarWidget(
      {Key key,
      this.hostTitle,
      this.type,
      this.tabItems,
      this.tabViews,
      this.backgroundColor,
      this.indicatorColor,
      this.title,
      this.initPage,
      this.onPageChanged})
      : super(key: key);

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _TabBarState(this.hostTitle, this.type, this.tabViews,
        this.indicatorColor, this.title, this.initPage, this.onPageChanged);
  }
}

class _TabBarState extends State<TabBarWidget>
    with SingleTickerProviderStateMixin {
  final String _hostTitle;
  final int _type;
  final int _initPage;
  final List<Widget> _tabViews;
  final Color _indicatorColor;
  final Widget _title;
  final ValueChanged<int> _onPageChanged;

  _TabBarState(this._hostTitle, this._type, this._tabViews,
      this._indicatorColor, this._title, this._initPage, this._onPageChanged)
      : super();
  TabController _tabController;
  PageController _pageController;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(
        initialIndex: _initPage,
        length: widget.tabItems == null ? 0 : widget.tabItems.length,
        vsync: this);
    _pageController = PageController(initialPage: _initPage, keepPage: true);
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _tabController.dispose();
    _pageController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (this._type == TabBarWidget.TOP_TAB) {
      return Scaffold(
        body: Column(
          children: <Widget>[
            TabBar(
              tabs: widget.tabItems,
              controller: _tabController,
              indicatorColor: _indicatorColor,
              indicatorSize: TabBarIndicatorSize.label,
              labelColor: Color(0xff23AFDC),
              unselectedLabelColor: Color(0xff999999),
              onTap: (index) {
                _pageController.jumpToPage(index);
              },
            ),
            Expanded(
              child: PageView(
                controller: _pageController,
                children: _tabViews,
                onPageChanged: (index) {
                  _tabController.animateTo(index);
                  _onPageChanged?.call(index);
                },
              ),
            ),
          ],
        ),
      );
    }
  }
}
